<template>
  <div id="app">
    <HelloWorld />

    <i class="el-icon-edit"></i>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="date" label="日期" width="180"> </el-table-column>
      <el-table-column prop="name" label="姓名" width="180"> </el-table-column>
      <el-table-column prop="sex" label="性别" width="180"> </el-table-column>
      <el-table-column prop="address" label="地址"> </el-table-column>
    </el-table>

    <el-button :loading="loading" @click="onClick">按钮</el-button>

    <div v-if="curSelectBanner.title">
      <p>{{ curSelectBanner.title }}</p>
      <img style="width: 100px" :src="curSelectBanner.imageUrl" alt="" />
    </div>

    <el-autocomplete
      v-model="searchValue"
      value-key="title"
      :fetch-suggestions="querySearchAsync"
      placeholder="请输入内容"
      @select="onSelect"
    ></el-autocomplete>
  </div>
</template>

<script>
import axios from "axios";
import { Button, Autocomplete } from "element-ui";
// console.log(Button);

import HelloWorld from "./components/HelloWorld.vue";

export default {
  name: "App",
  components: {
    HelloWorld,

    [Button.name]: Button,
    [Autocomplete.name]: Autocomplete,
  },

  data() {
    return {
      tableData: [
        {
          date: "2022-01-01",
          name: "张三",
          sex: "男",
          address: "深圳",
        },
      ],

      loading: false, // 是否在请求数据中

      searchValue: "", // 搜索关键字

      curSelectBanner: {}, // 当前选择的banner数据
    };
  },

  methods: {
    onClick() {
      // 判断当前是否在调用接口中
      if (this.loading) {
        return;
      }

      // 调用接口
      this.loading = true;
      console.log("onClick");
      setTimeout(() => {
        console.log("接口调用成功");

        this.loading = false;
      }, 2000);
    },

    querySearchAsync(queryString, cb) {
      // console.log("===", queryString, cb);
      // cb([
      //   { value: 100, address: "深圳" },
      //   { value: 200, address: "北京" },
      // ]);

      axios
        .get("http://localhost:3000/banners", {
          // get请求的第二个参数,是一个 config config中有一个 params 配置项,要传递参数的往这里写
          params: {
            title_like: queryString,
          },
        })
        .then(({ data }) => {
          console.log("接口调用成功", data);

          // data.data 中数据没有 value 值,需要添加一下将title做为value
          // const result = data.data.map((item) => {
          //   return {
          //     ...item,
          //     value: item.title,
          //   };
          // });

          // console.log(result);

          // cb(result);

          cb(data.data);
        })
        .catch((error) => {
          console.error("接口调用失败", error);
        });
    },

    onSelect(data) {
      this.curSelectBanner = data;
    },
  },
};
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
